package com.recipedb.sprint.controller;

import com.recipedb.sprint.security.JwtUtil;
import com.recipedb.sprint.service.RewardsService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/rewards")
public class RewardsController {

    private final RewardsService rewardsService;

    public RewardsController(RewardsService rewardsService) {
        this.rewardsService = rewardsService;
    }

    /**
     * 获取可兑换奖品列表
     */
    @GetMapping("/items")
    public ResponseEntity<Map<String, Object>> getAvailableRewards() {
        try {
            var data = rewardsService.getAvailableRewards();

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("data", data);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取奖品详情
     */
    @GetMapping("/items/{rewardId}")
    public ResponseEntity<Map<String, Object>> getRewardDetail(@PathVariable Long rewardId) {
        try {
            Map<String, Object> data = rewardsService.getRewardDetail(rewardId);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("data", data);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 兑换奖品
     */
    @PostMapping("/exchange")
    public ResponseEntity<Map<String, Object>> redeemReward(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> request) {
        try {
            // 1. 处理 Token 前缀
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            // 2. 解析 Token 获取 username
            String username = JwtUtil.validateToken(pureToken);
            if (username == null) {
                throw new RuntimeException("Token无效或已过期");
            }
            // 3. 假设通过 username 查询 userid（需 RewardsService 支持）
            Long userid = rewardsService.getUserIdByUsername(username);

            // 4. 提取请求参数
            Long rewardId = Long.valueOf(request.get("rewardId").toString());
            Integer quantity = request.get("quantity") != null ?
                    Integer.valueOf(request.get("quantity").toString()) : 1;

            Map<String, Object> data = rewardsService.redeemReward(userid, rewardId, quantity);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "兑换成功");
            response.put("data", data);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}